I updated mongoose to latest version (6.0.2) and now I'm recieving this error and crush the application whenever .updateOne() is executed. But object update inside the database. My code:
async(req,res) => {
await Todo.updateOne(
{_id : req.params.id},
{
$set : {
status : "inactive"
}
},
(updateError) => {
// if updateError exist
if (updateError) {
// print error
printError(updateError);
// response the error
res.status(500).json({
error : "There was a Server Side Error!"
});
} else {
// if error dose not exist
// print message
console.log("|===> 🗂️ Data Was Updated successfully! 🗂️ <====|\n");
// response success
res.json({
message : "Todo Was Update successfully!"
});
}
});
}
Try to add .clone() to de updateOne function
async(req,res) => {
await Todo.updateOne(
{_id : req.params.id},
{
$set : {
status : "inactive"
}
},
(updateError) => {
// if updateError exist
if (updateError) {
// print error
printError(updateError);
// response the error
res.status(500).json({
error : "There was a Server Side Error!"
});
} else {
// if error dose not exist
// print message
console.log("|===> 🗂️ Data Was Updated successfully! 🗂️ <====|\n");
// response success
res.json({
message : "Todo Was Update successfully!"
});
}
}).clone();
}
Latest version of mongoose not duplicate execution
https://mongoosejs.com/docs/migrating_to_6.html#duplicate-query-execution
Since you are using async syntax, put your code in try/catch blok:
async (req, res) => {
try {
await Todo.updateOne({ _id: req.params.id }, { $set: { status: "inactive"}});
res.status(200).json({message: "Todo Was Update successfully!"});
} catch (error) {
res.status(500).json({error:'There was a Server Side Error!'})
}
}
Your async/await should look like this:
async (req,res) => {
try {
const result = await Todo.updateOne(
{_id : req.params.id},
{
$set : {
status : "inactive"
}
},
);
}
console.log('success', result)
res.json({message: "Todo Was Update successfully!", result })
} catch (err) {
console.log('error', err)
res.status(500).json({error:'There was a Server Side Error!'})
}
}